package com.example.labapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Array;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.transform.Result;

public class examAct extends Activity implements CompoundButton.OnCheckedChangeListener {
    //一些必要的数据
    String stdId;
    String currentTestPaper="testPaper1";
    float lastGrade=0;
    Connection DBconn;
    Integer currentItem=0;
    Integer examResult=0; //用于统计得分

    //考试信息
    int examTime;
    int passGrade;
    int itemNums;
    int isRandom;

    //映射布局
    TextView txtExamLastTime;
    TextView txtExamTitle;
    TextView txtExamTips;
    Button btnExamLast,btnExamNext;
    LinearLayout lineExamSelect;
    LinkedList<itemData> listExamData=new LinkedList<itemData>();
    //一个对话框，用于等待
    AlertDialog loadDialog;
    AlertDialog.Builder loadDialogBuilder;
    myProgressDlg progressDlg;

    //定时器
    long timerCount=0;
    Timer timer=new Timer();
    TimerTask TimerTask=new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(timerAct);
        }
    };

    Runnable timerAct=new Runnable() {
        @Override
        public void run() {
            timerCount++;
            txtExamLastTime.setText(String.format("剩余时间: %d 分钟",examTime-timerCount));
            if(timerCount==examTime-10)
                Toast.makeText(examAct.this,"考试结束还剩10分钟",Toast.LENGTH_LONG).show();
            else if(timerCount==examTime-1)
                Toast.makeText(examAct.this,"考试将在1分钟后结束",Toast.LENGTH_LONG).show();
            else if(timerCount==examTime)
                examFinish();
        }
    };

    class singleSelected
    {
        String item;
        Boolean answer;

        Boolean isSelected;
    }

    class itemData
        //保存每个题目的数据
    {
        public String title;
        public Integer mode;  //1为单选，2为多选,3填空
        public ArrayList<singleSelected> selectArr=new ArrayList<>();
        Integer grade;
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b)
    {
        itemData changeData=listExamData.get(currentItem);
        singleSelected changeItem=changeData.selectArr.get((Integer)compoundButton.getTag());
        changeItem.isSelected=b;
        changeData.selectArr.set((Integer)compoundButton.getTag(),changeItem);
        listExamData.set(currentItem,changeData);
    }

    @Subscribe
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exam_lay);
        //注册Activity为订阅者
        EventBus.getDefault().register(this);
        //初始化UI
        InitUI();
        //获取从父Activity中传入的stdID
        stdId=getIntent().getStringExtra("stdID");
        currentTestPaper=getIntent().getStringExtra("Exam");
        lastGrade=getIntent().getFloatExtra("Grade",0);
        //用于初始化数据
        try {
            loadData();  //用于加载数据
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStop()
    {
        timer.cancel();
        super.onStop();
    }

    private void InitUI()
    {
        lineExamSelect=findViewById(R.id.linerExamSelected);
        txtExamTips=findViewById(R.id.txtExamTips);
        btnExamNext=findViewById(R.id.btnExamNext);
        txtExamTitle=findViewById(R.id.txtExamTitle);
        btnExamLast=findViewById(R.id.btnExamLast);
        txtExamLastTime=findViewById(R.id.txtExamLastTime);

        btnExamLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateUI(currentItem-1);
            }
        });

        btnExamNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateUI(currentItem+1);
            }
        });
    }

    AfterThread callbackLogin=(ErrorInf res)->
    {
        Looper.prepare();
        progressDlg.cancel();
        if(!res.status)
        {
            Toast.makeText(examAct.this,"数据加载失败，请重新进入",Toast.LENGTH_SHORT).show();
            finish();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateUI(0);
                timer.schedule(TimerTask,0,60000);  //设置定时时间
            }
        });
        Looper.loop();
    };

    private void loadData() throws InterruptedException {
        progressDlg=new myProgressDlg(examAct.this);
        progressDlg.setTitle("下载数据");
        progressDlg.setTxtMessage("正在加载题目");
        progressDlg.setProgressBarMaxValue(200);
        progressDlg.setProgressBarValue(0);
        progressDlg.setCancelable(false);
        progressDlg.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Class.forName("org.mariadb.jdbc.Driver");
                    DBconn = DriverManager.getConnection("jdbc:mariadb://124.222.159.110:3306/laboratory_APP?characterEncoding=utf-8/","labApp","3A9PvxE");
                    Statement stmt=DBconn.createStatement();
                    ResultSet resCount=stmt.executeQuery("SELECT count(Pnode) FROM "+currentTestPaper+" ;");
                    resCount.next();
                    int itemCount=resCount.getInt("count(Pnode)");  //获取题目总数
                    resCount=stmt.executeQuery(String.format("SELECT ExamTime,passGrade,itemNums,isRandom FROM appExams WHERE ExamName='%s';",currentTestPaper));
                    resCount.next();
                    examTime=resCount.getInt("ExamTime");
                    passGrade=resCount.getInt("passGrade");
                    itemNums=resCount.getInt("itemNums");
                    isRandom=resCount.getInt("isRandom");
                    Random rand=new Random();
                    for(int ixx=1;ixx<=itemNums;ixx++)  //题目数量
                    {
                        ResultSet res=null;
                        if(isRandom==1)
                            res=stmt.executeQuery("SELECT Ptitle,Poption FROM "+currentTestPaper+" WHERE Pnode="+rand.nextInt(itemCount)+" ;");  //随机抽取题目
                        else
                            res=stmt.executeQuery("SELECT Ptitle,Poption FROM "+currentTestPaper+" WHERE Pnode="+ixx+" ;");  //随机抽取题目
                        res.next();
                        itemData aitem=new itemData();
                        aitem.title=res.getString("Ptitle");
                        String selected=res.getString("Poption");  //这个是JSON字符串
                        JSONObject jsonObject= JSON.parseObject(selected);
                        List<String> newSelectLink=JSON.parseArray(jsonObject.getJSONArray("item").toJSONString(),String.class);
                        for (String i : newSelectLink) {
                            List<String> newSelectItem = JSON.parseArray(i, String.class);
                            singleSelected newSelected=new singleSelected();
                            newSelected.isSelected=false;
                            newSelected.item=newSelectItem.get(0);
                            String x=newSelectItem.get(1).toString();
                            if(newSelectItem.get(1).toString().charAt(0)=='1')
                                newSelected.answer=true;
                            else
                                newSelected.answer=false;
                            aitem.selectArr.add(newSelected);
                        }
                        aitem.mode=jsonObject.getInteger("aType");
                        aitem.grade=jsonObject.getInteger("Grade");
                        listExamData.add(aitem);
                        EventBus.getDefault().post(new updateProgressEvent(ixx));
                    }
                    DBconn.close();
                } catch (SQLException | ClassNotFoundException throwables) {
                    ErrorInf resData=new ErrorInf();
                    resData.status=false;
                    callbackLogin.callback(resData);
                }
                ErrorInf resData=new ErrorInf();
                resData.status=true;
                callbackLogin.callback(resData);
            }
        }).start();
    }

    //处理订阅事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateProgress(updateProgressEvent event)
    {
        progressDlg.setProgressBarValue(event.getValue());
    }

    private void updateUI(int position)
    {
        currentItem=position;
        if(position==listExamData.size())
        {
            examFinish();
            btnExamNext.setEnabled(false);
            btnExamLast.setEnabled(false);
            return;
        }
        if(position==listExamData.size()-1)
            btnExamNext.setText("提交");
        if(position==0)
            btnExamLast.setEnabled(false);
        else
            btnExamLast.setEnabled(true);

        itemData aitem=listExamData.get(position);
        //显示信息，告诉用户第几题了
        txtExamTitle.setText(aitem.title);
        txtExamTips.setText("题目"+(position+1)+"/"+listExamData.size());

        //清空元素，接下来重新布局
        lineExamSelect.removeAllViews();
        switch (aitem.mode)
        {
            case 1:
                //单选题
                RadioGroup singleSelect=new RadioGroup(examAct.this);
                lineExamSelect.addView(singleSelect);
                for(int i=0;i<aitem.selectArr.size();i++)
                {
                    RadioButton selectitem=new RadioButton(examAct.this);
                    selectitem.setTag(new Integer(i));
                    selectitem.setTextSize(20);
                    selectitem.setText(aitem.selectArr.get(i).item);
                    selectitem.setOnCheckedChangeListener(examAct.this);
                    singleSelect.addView(selectitem);
                }
                break;
            case 2:
                //多选题
                for(int i=0;i<aitem.selectArr.size();i++)
                {
                    CheckBox checkItem=new CheckBox(examAct.this);
                    checkItem.setText(aitem.selectArr.get(i).item);
                    checkItem.setTextSize(20);
                    checkItem.setTag(new Integer(i));
                    checkItem.setOnCheckedChangeListener(examAct.this);
                    lineExamSelect.addView(checkItem);
                }
                break;
        }
    }

    private void examFinish()
    {
        //销毁定时器
        timer.cancel();
        //用于统计总分，因为题目是随机抽取的，每个题目分数不一样，弄不好每个人总分都不一样，这里采用百分比方案
        Integer allResult=0;
        for(int i=0;i<listExamData.size();i++)
        {
            itemData aitem=listExamData.get(i);
            allResult+=2;
            switch (aitem.mode)
            {
                case 1:
                    for(int j=0;j<aitem.selectArr.size();j++)
                    {
                        if(aitem.selectArr.get(j).isSelected)
                        {
                            if(aitem.selectArr.get(j).answer)
                                examResult+=2;
                            break;
                        }
                    }
                    break;
                case 2:
                    Boolean noErr=new Boolean(Boolean.TRUE);
                    for(int j=0;j<aitem.selectArr.size();j++)
                    {
                        if(aitem.selectArr.get(j).answer)
                            if(!aitem.selectArr.get(j).isSelected)
                            {
                                noErr=false;
                                break;
                            }
                    }
                    if(noErr==true)
                        examResult+=2;
                    break;
            }
        }
        examResult=(int)((float)examResult/(float)allResult*100);  //重新分配分数
        loadDialog=null;
        loadDialogBuilder=new AlertDialog.Builder(examAct.this);
        loadDialogBuilder.setIcon(R.drawable.icon977);
        loadDialogBuilder.setMessage("成绩正在上传，稍安勿躁");
        loadDialogBuilder.setCancelable(false);
        loadDialog=loadDialogBuilder.create();
        loadDialog.show();
        Thread updateAchievement=new Thread(new Runnable() {
            @Override
            public void run() {
                boolean isTryAgain=true;
                while(isTryAgain)
                {
                    try {
                        DBconn = DriverManager.getConnection("jdbc:mariadb://124.222.159.110:3306/laboratory_APP?characterEncoding=utf-8/","labApp","3A9PvxE");
                        Statement stmt=DBconn.createStatement();
                        if(lastGrade<examResult)
                            stmt.execute("UPDATE StudUser SET "+currentTestPaper+"="+examResult+" WHERE StdID="+stdId+";");
                        //增加一次作答次数
                        stmt.execute(String.format("UPDATE examAnswerNum SET %s=(%s+1) WHERE stdID=%s;",currentTestPaper,currentTestPaper,stdId));
                        isTryAgain=false; //如果上传异常就重新传输
                        DBconn.close();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadDialog=null;
                        loadDialogBuilder.setIcon(R.drawable.icon977);
                        loadDialogBuilder.setMessage("本次得分为: "+examResult);
                        loadDialogBuilder.setCancelable(false);
                        loadDialogBuilder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                examAct.this.finish();
                            }
                        });
                        loadDialog=loadDialogBuilder.create();
                        loadDialog.show();
                    }
                });
            }
        });
        updateAchievement.start();
    }
}
